# Create your views here.
from django.views.generic.list_detail import object_list, object_detail
from wal.familias.models import Familia
from wal.familias.forms import FamiliasForm
from wal.pedidos.forms import SearchForm
from django.template.context import RequestContext
from django.shortcuts import render_to_response
#from wal.views import update_object, create_object , delete_object
from django.views.generic.create_update import update_object, create_object , delete_object
from django.core.exceptions import ObjectDoesNotExist
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from wal.views import split_query_into_keywords
from django.db.models import Q

def obtenerFamilia(request,object_id):
    if int(object_id):
        try:
            objectoFamilia = Familia.objects.get(id=object_id)
        except ObjectDoesNotExist:
            return 'No existe el objecto'
    else:
        return 'No existe el objecto'
    return objectoFamilia

def listar(request,ot,o,page):
    
    request.breadcrumbs([('Familias',request.path)])
    
    if ot=='asc':
        if int(o) == 1:
            orden = "-nombre"
        elif int(o) == 2:
            orden = "-descripcion"
        else:
            orden = "-nombre"
    elif ot=='desc':
        if int(o) == 1:
            orden = "nombre"
        elif int(o) == 2:
            orden = "descripcion"
        else:
            orden = "nombre"
    else:
        orden = "-nombre"
    if request.method == 'GET':
        form = SearchForm(request.GET)
        if form.is_valid():
            keywords = form.cleaned_data['keywords']
            keyword_list = split_query_into_keywords(keywords)
            familias = search_for_keywords(keyword_list)
            if familias:
                # Show the results
                qs = familias.order_by(orden)
            else:
                qs = Familia.objects.none()
            form = SearchForm()
            return object_list(request,
                   queryset = qs,
                   allow_empty = True,
                   template_name = 'familias/listar.html',
                   extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                   paginate_by = 20,
                   page = page,
                   )
    else:
        form = SearchForm()
    return object_list(request,
                       queryset = Familia.objects.order_by(orden),
                       allow_empty = True,
                       template_name = 'familias/listar.html',
                       extra_context = {'ot':ot,'o':o,'page':page,'form':form},
                       paginate_by = 20,
                       page = page,
                       )
    
def ver(request, object_id):
    familia = obtenerFamilia(request, object_id)
    if familia == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    request.breadcrumbs([('Familias',reverse(listar,args=['asc',1,1])),(familia.nombre,request.path)])
    return render_to_response('familias/detalles.html', {'familia': familia}, context_instance=RequestContext(request))

def crear(request):
#    if request.method == "POST":
#        pform = ArticulosForm(request.POST, instance=Articulo())
#        if pform.is_valid():
#            new_articulo = pform.save()
#            return HttpResponseRedirect(reverse(ver, args=[new_articulo.id]))
#    else:
#        pform = ArticulosForm(instance=Articulo())
#    return render_to_response('articulos/articulo.html', {'form': pform}, context_instance=RequestContext(request))
    request.breadcrumbs([('Familias',reverse(listar,args=['asc',1,1])),('Crear',request.path)])
    return create_object(request,
                         model = Familia, 
                         form_class = FamiliasForm,
                         template_name = 'familias/familia.html', 
                         post_save_redirect = '/wal/familias/listar/ot=asc&o=1&page=1'
                         )

def editar(request, object_id):
    familia = obtenerFamilia(request, object_id)
    if familia == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    request.breadcrumbs([('Familias',reverse(listar,args=['asc',1,1])),('Editar '+familia.nombre,request.path)])
    return update_object(request,
                        model = Familia, 
                        #form_class = PedidosForm,
                        template_name = 'familias/familia.html', 
                        post_save_redirect = reverse(ver,args=[object_id]),
                        object_id = object_id
                        )
    
def borrar(request, object_id,ot,o,page):
    familia = obtenerFamilia(request, object_id)
    if familia == 'No existe el objecto':
        return render_to_response('error.html',{'error':'No existe el objecto'})
    return delete_object(request,
                         model = Familia, 
                         template_name = 'familias/confirm_delete_familia.html', 
                         post_delete_redirect = reverse(listar, args=[ot,o,page]),
                         object_id = object_id
                         )
    
def search_for_keywords(keywords):
    """Make a search that contains all of the keywords."""
    familias = Familia.objects.all()
    for keyword in keywords:
        familias = familias.filter(Q(nombre__icontains=keyword)|Q(descripcion__icontains=keyword))
    return familias

